/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.purchase.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.purchase.entity.ErpPurchaseContract;
import com.thinkgem.jeesite.modules.purchase.dao.ErpPurchaseContractDao;
import com.thinkgem.jeesite.modules.purchase.entity.ErpPurchaseContractSub;
import com.thinkgem.jeesite.modules.purchase.dao.ErpPurchaseContractSubDao;

/**
 * 采购合同Service
 * @author 孙佳亮
 * @version 2016-06-03
 */
@Service
@Transactional(readOnly = true)
public class ErpPurchaseContractService extends CrudService<ErpPurchaseContractDao, ErpPurchaseContract> {

	@Autowired
	private ErpPurchaseContractSubDao erpPurchaseContractSubDao;
	
	public ErpPurchaseContract get(String id) {
		ErpPurchaseContract erpPurchaseContract = super.get(id);
		erpPurchaseContract.setErpPurchaseContractSubList(erpPurchaseContractSubDao.findList(new ErpPurchaseContractSub(erpPurchaseContract)));
		return erpPurchaseContract;
	}
	
	public List<ErpPurchaseContract> findList(ErpPurchaseContract erpPurchaseContract) {
		return super.findList(erpPurchaseContract);
	}
	
	public Page<ErpPurchaseContract> findPage(Page<ErpPurchaseContract> page, ErpPurchaseContract erpPurchaseContract) {
		return super.findPage(page, erpPurchaseContract);
	}
	
	@Transactional(readOnly = false)
	public void save(ErpPurchaseContract erpPurchaseContract) {
		super.save(erpPurchaseContract);
		for (ErpPurchaseContractSub erpPurchaseContractSub : erpPurchaseContract.getErpPurchaseContractSubList()){
			if (erpPurchaseContractSub.getId() == null){
				continue;
			}
			if (ErpPurchaseContractSub.DEL_FLAG_NORMAL.equals(erpPurchaseContractSub.getDelFlag())){
				if (StringUtils.isBlank(erpPurchaseContractSub.getId())){
					erpPurchaseContractSub.setErpPurchaseContractId(erpPurchaseContract);
					erpPurchaseContractSub.preInsert();
					erpPurchaseContractSubDao.insert(erpPurchaseContractSub);
				}else{
					erpPurchaseContractSub.preUpdate();
					erpPurchaseContractSubDao.update(erpPurchaseContractSub);
				}
			}else{
				erpPurchaseContractSubDao.delete(erpPurchaseContractSub);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(ErpPurchaseContract erpPurchaseContract) {
		super.delete(erpPurchaseContract);
		erpPurchaseContractSubDao.delete(new ErpPurchaseContractSub(erpPurchaseContract));
	}
	
}